import { message } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';

import knowService from '@/api/services/knowService';
import PagesHeader from '@/components/pages-header';
import { useParams } from '@/router/hooks';

import DataOverviewHeader from '../components/DataOverviewHeader';

import Expired from './expired';
import Feedback from './feedback';
import Frequency from './frequency';
import FrequencyList from './frequencyList';
import Unknown from './unknown';

const tooltipMap: Record<string, string> = {
  AIAnswer: '统计AI在用户提问中未能给出有效回答的问题数量，用于衡量知识库覆盖程度和AI应答能力。',
  usersQuestions: '记录用户对AI回答表示不满意的问题数量，反映回答质量与用户预期的差距。',
  documentFresh: '表示当前知识库中文档是否即将过期，过期文档可能影响回答准确性和时效性。',
  document: '当前知识库中累计的文档总量，包含所有已上传的文档。',
  documentProportion:
    '反映在问答过程中被频繁引用的文档所占比例，高占比说明少量文档对问答效果影响较大。',
  documentRanking: '展示被引用次数最多的文档列表，有助于识别核心知识内容及高价值文档。',
};
interface KnowGovDataOverviewProps {
  handleMenuClick: (e: { key: string }) => void;
}

const KnowGovDataOverview = ({ handleMenuClick }: KnowGovDataOverviewProps) => {
  const { appId = '' } = useParams() as { appId: string };
  const [statisticsLoading, setStatisticsLoading] = useState(false);
  const [activeRange, setActiveRange] = useState('7days');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(6, 'day'),
    dayjs(),
  ]);
  const [total, setTotal] = useState(0);
  const [paginationProps, setPaginationProps] = useState({
    appId,
    startTime: dateRange[0].format('YYYY-MM-DD'),
    endTime: dateRange[1].format('YYYY-MM-DD'),
    page: 1,
    pageSize: 10,
    offset: 0,
  });
  const [unknownAsked, setUnknownAsked] = useState({
    unknownCount: 0,
    percent: 0,
    isRise: true,
    data: [],
  });
  const [feedbackData, setFeedbackData] = useState({
    feedbackCount: 0,
    percent: 0,
    isRise: true,
    data: [],
    solvedNum: 0,
    unsolvedNum: 0,
    solvedPercent: 0,
    unsolvedPercent: 0,
    isSolvedRise: true,
    isUnsolvedRise: true,
  });
  const [expiredData, setExpiredData] = useState({
    expiredCount: 0,
    expiredPercent: 0,
    normalPercent: 0,
    prevExpiredPercent: 0,
  });
  const [frequencyData, setFrequencyData] = useState({
    fileTotal: 0,
    highFrequency: 0,
    isRise: true,
    lowFrequency: 0,
    period_total: 0,
    risePercent: 0,
  });
  const [frequencyDataList, setFrequencyDataList] = useState([]);

  useEffect(() => {
    if (appId) {
      handleUnknowCount(
        appId,
        dateRange[0].format('YYYY-MM-DD'),
        dateRange[1].format('YYYY-MM-DD'),
      );
      handleFeedbackCount(
        appId,
        dateRange[0].format('YYYY-MM-DD'),
        dateRange[1].format('YYYY-MM-DD'),
      );
      handleExpiredCount(
        appId,
        dateRange[0].format('YYYY-MM-DD'),
        dateRange[1].format('YYYY-MM-DD'),
      );
      handleFrequency(appId, dateRange[0].format('YYYY-MM-DD'), dateRange[1].format('YYYY-MM-DD'));
    }
  }, [dateRange, appId]);
  useEffect(() => {
    handleFrequencyList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [paginationProps, dateRange]);

  const handleUnknowCount = async (appId: string, startDate: string, endDate: string) => {
    try {
      setStatisticsLoading(true);
      const res = await knowService.getunknowCount({
        appId,
        startTime: startDate,
        endTime: endDate,
        // appId: '67ed1efaf0c96cbd068e4570',
        // startTime: '2025-07-23',
        // endTime: '2025-07-29',
      });
      // res.unknownCount = 10;
      // res.percent = 0.5;
      // res.isRise = true;
      // res.data[0].unknownCount = 2;
      // res.data[1].unknownCount = 4;
      // res.data[2].unknownCount = 6;
      // res.data[3].unknownCount = 10;
      // res.data[4].unknownCount = 8;
      // res.data[5].unknownCount = 6;
      // res.data[6].unknownCount = 2;
      if (res.percent !== '-') {
        res.percent = Number(res.percent);
      }
      setUnknownAsked(res);
    } catch (error) {
      console.log(error);
    } finally {
      setStatisticsLoading(false);
    }
  };
  const handleFeedbackCount = async (appId: string, startDate: string, endDate: string) => {
    try {
      setStatisticsLoading(true);
      const res = await knowService.getfeedbackCount({
        appId,
        startTime: startDate,
        endTime: endDate,
      });
      // res.feedbackCount = 10;
      // res.percent = 0.5;
      // res.isRise = true;
      // res.data[0].feedbackCount = 2;
      // res.data[1].feedbackCount = 4;
      // res.data[2].feedbackCount = 6;
      // res.data[3].feedbackCount = 10;
      if (res.percent !== '-') {
        res.percent = Number(res.percent);
      }
      setFeedbackData(res);
    } catch (error) {
      console.log(error);
    } finally {
      setStatisticsLoading(false);
    }
  };
  const handleExpiredCount = async (appId: string, startDate: string, endDate: string) => {
    try {
      setStatisticsLoading(true);
      const res = await knowService.getExpiredCount({
        appId,
        startTime: startDate,
        endTime: endDate,
      });

      // res.expiredCount = 10; //总数
      // res.expiredPercent = 0.2; //即将过期
      // res.normalPercent = 0.8; //常规
      res.expiredPercent = Number((res.expiredPercent * 100).toFixed(2));
      res.normalPercent = Number((res.normalPercent * 100).toFixed(2));
      res.prevExpiredPercent = Number((res.prevExpiredPercent * 100).toFixed(2));
      setExpiredData(res);
    } catch (error) {
      console.log(error);
    } finally {
      setStatisticsLoading(false);
    }
  };
  const handleFrequency = async (appId: string, startDate: string, endDate: string) => {
    try {
      setStatisticsLoading(true);
      const res = await knowService.getFrequency({
        appId,
        startTime: startDate,
        endTime: endDate,
      });
      // res.fileTotal = 100;
      // res.highFrequency = 0.5;
      // res.isRise = true;
      // res.lowFrequency = 0.5;
      // res.period_total = 100;
      // res.risePercent = 0.5;
      res.highFrequency = Number((res.highFrequency * 100).toFixed(2));
      res.lowFrequency = Number((res.lowFrequency * 100).toFixed(2));
      setFrequencyData(res);
    } catch (error) {
      console.log(error);
    } finally {
      setStatisticsLoading(false);
    }
  };
  const handleFrequencyList = async () => {
    try {
      setStatisticsLoading(true);
      const res = await knowService.getFrequencyList(paginationProps);
      setTotal(res.total);
      setFrequencyDataList(res.data);
    } catch (error) {
      console.log(error);
    } finally {
      setStatisticsLoading(false);
    }
  };

  const handleQuickSelect = (days: number, activeRange: string = '' as string) => {
    const endDate = dayjs().startOf('day');
    const startDate = endDate.subtract(days - 1, 'days').startOf('day');
    setDateRange([startDate, endDate]);
    setPaginationProps({
      ...paginationProps,
      startTime: startDate.format('YYYY-MM-DD'),
      endTime: endDate.format('YYYY-MM-DD'),
    });
    setActiveRange(activeRange);
  };
  const handleDateChange = (dates: [dayjs.Dayjs, dayjs.Dayjs]) => {
    if (dates && dates.length === 2) {
      const [start, end] = dates;
      const diffDays = end.diff(start, 'day');
      if (diffDays > 29) {
        const adjustedStart = end.subtract(29, 'day');
        setDateRange([adjustedStart, end]);
        setPaginationProps({
          ...paginationProps,
          startTime: adjustedStart.format('YYYY-MM-DD'),
          endTime: end.format('YYYY-MM-DD'),
        });
        message.info('超出30天，按照近30天展示');
      } else {
        setDateRange([start, end]);
        setPaginationProps({
          ...paginationProps,
          startTime: start.format('YYYY-MM-DD'),
          endTime: end.format('YYYY-MM-DD'),
        });
      }
      if (diffDays !== 29 && diffDays !== 6) {
        setActiveRange('days');
      }
    }
  };

  return (
    <div className="flex h-full flex-col">
      <div className="mb-2 flex h-[64px] items-center justify-between rounded-default bg-white px-5 py-2">
        <PagesHeader className="!m-0 !p-0">数据总览</PagesHeader>
        <DataOverviewHeader
          handleDateChange={handleDateChange}
          handleQuickSelect={handleQuickSelect}
          dateRange={dateRange}
          activeRange={activeRange}
        />
      </div>
      <div className="mb-2 flex h-[370px] gap-2">
        {/* 未知问 */}
        <Unknown
          unknownAsked={unknownAsked}
          statisticsLoading={statisticsLoading}
          tooltipMap={tooltipMap}
          activeRange={activeRange}
          onShowDetail={() => {
            handleMenuClick({ key: 'ai-unanswerable' });
          }}
        />
        {/* 点踩问 */}
        <Feedback
          feedbackData={feedbackData}
          statisticsLoading={statisticsLoading}
          tooltipMap={tooltipMap}
          activeRange={activeRange}
          onShowDetail={() => {
            handleMenuClick({ key: 'user-dislike' });
          }}
        />
        {/* 文档新鲜度 */}
        <Expired
          expiredData={expiredData}
          statisticsLoading={statisticsLoading}
          tooltipMap={tooltipMap}
          activeRange={activeRange}
          onShowDetail={() => {
            handleMenuClick({ key: 'fresh-knowledge' });
          }}
        />
      </div>
      <div className="flex w-full  flex-1 gap-2">
        {/* 文档新鲜占比 */}
        <Frequency
          frequencyData={frequencyData}
          statisticsLoading={statisticsLoading}
          tooltipMap={tooltipMap}
          activeRange={activeRange}
        />
        {/* 高频文档排行 */}
        <FrequencyList
          frequencyDataList={frequencyDataList}
          statisticsLoading={statisticsLoading}
          tooltipMap={tooltipMap}
          currentPage={paginationProps.page}
          pageSize={paginationProps.pageSize}
          total={total}
          onPageChange={(page, pageSize) => {
            setPaginationProps({
              ...paginationProps,
              page,
              pageSize,
              offset: (page - 1) * pageSize,
            });
          }}
        />
      </div>
    </div>
  );
};
export default KnowGovDataOverview;
